<template>
  <div class="p-2">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>入住流程记录</span>
          <div class="right-buttons">
            <el-button type="primary" plain @click="handleAdd">
              <el-icon><plus /></el-icon>新增
            </el-button>
            <el-button type="success" plain @click="handleReview">
              <el-icon><check /></el-icon>审核
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="老人ID" prop="elderId">
          <el-input v-model="queryParams.elderId" placeholder="请输入老人ID" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="当前步骤" prop="step">
          <el-input v-model="queryParams.step" placeholder="请输入当前步骤" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="未开始" value="未开始" />
            <el-option label="进行中" value="进行中" />
            <el-option label="已完成" value="已完成" />
            <el-option label="已取消" value="已取消" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态" prop="reviewStatus">
          <el-select v-model="queryParams.reviewStatus" placeholder="请选择审核状态" clearable>
            <el-option label="待审核" value="待审核" />
            <el-option label="已通过" value="已通过" />
            <el-option label="已驳回" value="已驳回" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><search /></el-icon>搜索
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table v-loading="loading" :data="admissionProcessList">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="流程ID" align="center" prop="processId" />
        <el-table-column label="老人ID" align="center" prop="elderId" />
        <el-table-column label="当前步骤" align="center" prop="step" />
        <el-table-column label="状态" align="center" prop="status" />
        <el-table-column label="审核状态" align="center" prop="reviewStatus">
          <template #default="scope">
            <el-tag v-if="scope.row.reviewStatus === '待审核'" type="warning">待审核</el-tag>
            <el-tag v-else-if="scope.row.reviewStatus === '已通过'" type="success">已通过</el-tag>
            <el-tag v-else-if="scope.row.reviewStatus === '已驳回'" type="danger">已驳回</el-tag>
            <span v-else>{{ scope.row.reviewStatus }}</span>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" align="center" prop="startTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="完成时间" align="center" prop="endTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120">
          <template #default="scope">
            <el-button type="text" @click="handleSelect(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 添加或修改入住流程记录对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="admissionProcessFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="老人ID" prop="elderId">
          <el-input v-model="form.elderId" placeholder="请输入老人ID" />
        </el-form-item>
        <el-form-item label="当前步骤" prop="step">
          <el-input v-model="form.step" placeholder="请输入当前步骤" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="未开始" value="未开始" />
            <el-option label="进行中" value="进行中" />
            <el-option label="已完成" value="已完成" />
            <el-option label="已取消" value="已取消" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker v-model="form.startTime" type="datetime" placeholder="请选择开始时间" />
        </el-form-item>
        <el-form-item label="完成时间" prop="endTime">
          <el-date-picker v-model="form.endTime" type="datetime" placeholder="请选择完成时间" />
        </el-form-item>
        <el-form-item label="经办人" prop="handler">
          <el-input v-model="form.handler" placeholder="请输入经办人" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog title="入住流程详情" v-model="detailDialog.visible" width="700px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="流程ID">{{ detailForm.processId }}</el-descriptions-item>
        <el-descriptions-item label="老人ID">{{ detailForm.elderId }}</el-descriptions-item>
        <el-descriptions-item label="当前步骤">{{ detailForm.step }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ detailForm.status }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ parseTime(detailForm.startTime) }}</el-descriptions-item>
        <el-descriptions-item label="完成时间">{{ parseTime(detailForm.endTime) }}</el-descriptions-item>
        <el-descriptions-item label="经办人">{{ detailForm.handler }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ detailForm.remarks }}</el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <el-tag v-if="detailForm.reviewStatus === '待审核'" type="warning">待审核</el-tag>
          <el-tag v-else-if="detailForm.reviewStatus === '已通过'" type="success">已通过</el-tag>
          <el-tag v-else-if="detailForm.reviewStatus === '已驳回'" type="danger">已驳回</el-tag>
          <span v-else>{{ detailForm.reviewStatus }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="审核人">{{ detailForm.reviewerName }}</el-descriptions-item>
        <el-descriptions-item label="审核时间" :span="2">{{ parseTime(detailForm.reviewTime) }}</el-descriptions-item>
        <el-descriptions-item label="审核意见" :span="2">{{ detailForm.reviewComments }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AdmissionProcess" lang="ts">
import { listAdmissionProcess, getAdmissionProcess, addAdmissionProcess, updateAdmissionProcess, delAdmissionProcess } from '@/api/nursing/admissionProcess';
import { AdmissionProcessVO, AdmissionProcessForm, AdmissionProcessQuery } from '@/api/nursing/admissionProcess/types';
import { getCurrentInstance, reactive, ref, onMounted } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { useRouter } from 'vue-router';
import request from '@/utils/request';

const { proxy } = getCurrentInstance() as any;
const router = useRouter();

// 列表数据
const loading = ref(false);
const total = ref(0);
const admissionProcessList = ref<AdmissionProcessVO[]>([]);

// 查询参数
const queryParams = reactive<AdmissionProcessQuery>({
  pageNum: 1,
  pageSize: 10,
  elderId: undefined,
  step: undefined,
  status: undefined,
  reviewStatus: undefined,
});

// 表单参数
const dialog = reactive({
  visible: false,
  title: ''
});

// 详情对话框
const detailDialog = reactive({
  visible: false
});

// 表单对象
const admissionProcessFormRef = ref<FormInstance>();
const form = reactive<AdmissionProcessForm>({
  processId: undefined,
  elderId: undefined,
  step: undefined,
  status: undefined,
  startTime: undefined,
  endTime: undefined,
  handler: undefined,
  remarks: undefined
});

// 详情表单
const detailForm = reactive<AdmissionProcessVO>({} as AdmissionProcessVO);

// 表单校验规则
const rules = reactive<FormRules>({
  elderId: [
    { required: true, message: '老人ID不能为空', trigger: 'blur' }
  ],
  step: [
    { required: true, message: '当前步骤不能为空', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '状态不能为空', trigger: 'change' }
  ]
});

/** 查询入住流程记录列表 */
const getList = async () => {
  try {
    loading.value = true;
    const res = await listAdmissionProcess(queryParams);
    admissionProcessList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('获取入住流程记录列表失败', error);
    proxy.$modal.msgError('获取入住流程记录列表失败');
  } finally {
    loading.value = false;
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.elderId = undefined;
  queryParams.step = undefined;
  queryParams.status = undefined;
  queryParams.reviewStatus = undefined;
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = () => {
  resetForm();
  dialog.title = '添加入住流程记录';
  dialog.visible = true;
};

/** 修改按钮操作 */
const handleUpdate = async (row: AdmissionProcessVO) => {
  try {
    resetForm();
    const res = await getAdmissionProcess(row.processId);
    Object.assign(form, res.data);
    dialog.title = '修改入住流程记录';
    dialog.visible = true;
  } catch (error) {
    console.error('获取入住流程记录详情失败', error);
    proxy.$modal.msgError('获取入住流程记录详情失败');
  }
};

/** 提交按钮操作 */
const submitForm = async () => {
  try {
    await admissionProcessFormRef.value?.validate();

    if (form.processId) {
      await updateAdmissionProcess(form);
      proxy.$modal.msgSuccess('修改成功');
    } else {
      await addAdmissionProcess(form);
      proxy.$modal.msgSuccess('新增成功');
    }

    dialog.visible = false;
    getList();
  } catch (error) {
    console.error('提交失败', error);
    proxy.$modal.msgError('提交失败');
  }
};

/** 删除按钮操作 */
const handleDelete = async (row: AdmissionProcessVO) => {
  try {
    await proxy.$modal.confirm('是否确认删除该入住流程记录？');
    await delAdmissionProcess(row.processId);
    proxy.$modal.msgSuccess('删除成功');
    getList();
  } catch (error) {
    console.error('删除失败', error);
  }
};

/** 查看详情 */
const handleDetail = (row: AdmissionProcessVO) => {
  Object.assign(detailForm, row);
  detailDialog.visible = true;
};

/** 跳转到审核页面 */
const handleReview = () => {
  router.push('/nursing/admissionProcess/review');
};

/** 重置表单 */
const resetForm = () => {
  form.processId = undefined;
  form.elderId = undefined;
  form.step = undefined;
  form.status = undefined;
  form.startTime = undefined;
  form.endTime = undefined;
  form.handler = undefined;
  form.remarks = undefined;
};

// 在搜索老人的时候，添加过滤条件
const searchElders = (query) => {
  const params = {
    elderName: query,
    roomId: null,  // 只查找未分配房间的老人
    isActive: 0,    // 只查找未在院的老人
    reviewStatus: '1'  // 只查找审核通过的老人记录
  };

  return request({
    url: '/nursing/elderBasic/list',
    method: 'get',
    params
  }).then(res => {
    return res.rows.map(item => ({
      value: item.elderId,
      label: item.elderName,
      item
    }));
  });
}

// 添加handleSelect方法
const handleSelect = (row) => {
  // 处理选择老人的逻辑，例如设置所选老人信息到表单
  form.elderId = row.elderId;
  form.elderName = row.elderName;

  // 跳转到入住流程详细页面
  router.push({
    path: '/nursing/admissionProcess/detail',
    query: { id: row.processId }
  });
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.right-buttons {
  display: flex;
  gap: 10px;
}
</style>